﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

public partial class lottery_input : System.Web.UI.Page
{
    bool isImage;
    protected ArrayList ItemList_year = new ArrayList();
    protected ArrayList ItemList_month = new ArrayList();
    protected ArrayList ItemList_day = new ArrayList();
    protected ArrayList ItemList_hour = new ArrayList();
    protected ArrayList ItemList_minute = new ArrayList();
    protected ArrayList ItemList_second = new ArrayList();
    /// <summary>
    /// 文件上传函数
    /// </summary>
    /// <param name="path"></param>
    /// <param name="fileupload"></param>
    public void upload(string path, System.Web.UI.WebControls.FileUpload fileupload, string product_id)
    {
        bool fileok = false;
        if (fileupload.HasFile)
        {
            string fileException = System.IO.Path.GetExtension(fileupload.FileName).ToLower();
            string[] allowedException = { ".jpg", ".bmp", ".gif" };
            for (int i = 0; i < allowedException.Length; i++)
            {
                if (fileException == allowedException[i])
                    fileok = true;
            }
        }
        if (fileok)
        {
            if (System.IO.Directory.Exists(path))
            {
            }
            else
            {
                System.IO.Directory.CreateDirectory(path);
            }

            fileupload.SaveAs(path + "\\" + product_id + "_" + "image_tmp.jpg");
            isImage = true;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["USERNAME"] == null)
        {
            Response.Redirect("error_log.aspx", true);
        }
        if (Session["IDENTITY"].Equals("employee") == true)
        {
            Response.Redirect("error_auth.aspx", true);
        }
        if (!IsPostBack)
        {
            ItemList_year.Add(2013);
            ItemList_year.Add(2014);

            for (int m = 1; m < 13; m++)
                ItemList_month.Add(m);

            for (int d = 1; d < 32; d++)
                ItemList_day.Add(d);

            for (int h = 0; h < 24; h++)
                ItemList_hour.Add(h);

            for (int mi = 0; mi < 60; mi++)
                ItemList_minute.Add(mi);

            for (int s = 0; s < 60; s++)
                ItemList_second.Add(s);

            DropDownList1.DataBind();
            DropDownList2.DataBind();
            DropDownList3.DataBind();
            DropDownList4.DataBind();
            DropDownList5.DataBind();
            DropDownList6.DataBind();
            DropDownList7.DataBind();
            DropDownList8.DataBind();
            DropDownList9.DataBind();
            DropDownList10.DataBind();
            DropDownList11.DataBind();
            DropDownList12.DataBind();
        }
    }
    protected void button1_Click(object sender, EventArgs e)
    {
        int start_year;
        int start_month;
        int start_day;
        int start_hour;
        int start_minute;
        int start_second;
        int end_year;
        int end_month;
        int end_day;
        int end_hour;
        int end_minute;
        int end_second;
        if (img1.ImageUrl != null && img1.ImageUrl != "")
        {
            SqlConnection sc = new SqlConnection(ConfigurationManager.ConnectionStrings["wbkpt"].ConnectionString.ToString());
            sc.Open();
            if (textbox1.Text.Length == 0 || textbox1.Text.Length > 25)
            {
                sc.Close();
                Page.RegisterStartupScript("ss", "<script>alert('输入合适长度的标题！')</script>");
                return;
            }
            string fprize_name = textbox3.Text;
            string sprize_name = textbox5.Text;
            string tprize_name = textbox7.Text;
            string fprize_id="";
            string sprize_id="";
            string tprize_id="";

            int sum_expect;
            int fprize_sum;
            int sprize_sum;
            int tprize_sum;
            try
            {
                sum_expect = Convert.ToInt32(textbox2.Text);
                fprize_sum = Convert.ToInt32(textbox4.Text);
                sprize_sum = Convert.ToInt32(textbox6.Text);
                tprize_sum = Convert.ToInt32(textbox8.Text);
            }
            catch (Exception ex_sql)
            {
                sc.Close();
                Page.RegisterStartupScript("ss", "<script>alert('输入的数量必须为整数，请重新输入！')</script>");
                return;
            }

            #region 验证三个等级奖品是否存在，并获取ID
            SqlCommand check_fprize = new SqlCommand("select PRODUCT_ID from INFO_PRODUCT where PRODUCT_NAME=@fname and ENTER_ID=@eid1", sc);
            check_fprize.Parameters.AddWithValue("@fname",fprize_name);
            check_fprize.Parameters.AddWithValue("@eid1",Session["ENTERID"].ToString());
            object f1 = check_fprize.ExecuteScalar();
            if (f1 == null)
            {//
                sc.Close();
                Page.RegisterStartupScript("ss", "<script>alert('输入的一等奖奖品有误，请重新输入！')</script>");
                return;
            }
            else fprize_id = f1.ToString();

            SqlCommand check_sprize = new SqlCommand("select PRODUCT_ID from INFO_PRODUCT where PRODUCT_NAME=@sname and ENTER_ID=@eid2", sc);
            check_sprize.Parameters.AddWithValue("@sname", sprize_name);
            check_sprize.Parameters.AddWithValue("@eid2", Session["ENTERID"].ToString());
            object f2 = check_sprize.ExecuteScalar();
            if (f2 == null)
            {//
                sc.Close();
                Page.RegisterStartupScript("ss", "<script>alert('输入的二等奖奖品有误，请重新输入！')</script>");
                return;
            }
            else sprize_id = f2.ToString();

            SqlCommand check_tprize = new SqlCommand("select PRODUCT_ID from INFO_PRODUCT where PRODUCT_NAME=@tname and ENTER_ID=@eid3", sc);
            check_tprize.Parameters.AddWithValue("@tname", tprize_name);
            check_tprize.Parameters.AddWithValue("@eid3", Session["ENTERID"].ToString());
            object f3 = check_tprize.ExecuteScalar();
            if (f3 == null)
            {//
                sc.Close();
                Page.RegisterStartupScript("ss", "<script>alert('输入的三等奖奖品有误，请重新输入！')</script>");
                return;
            }
            else tprize_id = f3.ToString();
            #endregion


            start_year = Convert.ToInt32(DropDownList1.Text);
            start_month = Convert.ToInt32(DropDownList2.Text);
            start_day = Convert.ToInt32(DropDownList3.Text);
            start_hour = Convert.ToInt32(DropDownList4.Text);
            start_minute = Convert.ToInt32(DropDownList5.Text);
            start_second = Convert.ToInt32(DropDownList6.Text);
            end_year = Convert.ToInt32(DropDownList7.Text);
            end_month = Convert.ToInt32(DropDownList8.Text);
            end_day = Convert.ToInt32(DropDownList9.Text);
            end_hour = Convert.ToInt32(DropDownList10.Text);
            end_minute = Convert.ToInt32(DropDownList11.Text);
            end_second = Convert.ToInt32(DropDownList12.Text);
            if (isLegal(start_year, start_month, start_day, start_hour, start_minute, start_second) == true && isLegal(end_year, end_month, end_day, end_hour, end_minute, end_second) == true)
            {
                //检验日期先后是否合法
                if (checkSequence(start_year, start_month, start_day, start_hour, start_minute, start_second, end_year, end_month, end_day, end_hour, end_minute, end_second) == false)
                {
                    Page.RegisterStartupScript("ss", "<script>alert('开始日期在结束日期之后，请检查后确认！')</script>");
                    return;
                }

            }
            else
            {
                //开始或结束日期不合法，请检查后确认
                Page.RegisterStartupScript("ss", "<script>alert('开始或结束日期不合法，请检查后确认！')</script>");
                return;
            }

            if (textbox9.Text.Length > 300 || textbox9.Text.Length == 0)
            {
                Page.RegisterStartupScript("ss", "<script>alert('规则长度超过限制或没有内容，请检查后确认！')</script>");
                return;
            }
           
            string enterid = Session["ENTERID"].ToString();

            #region generate new id
            SqlCommand com1 = new SqlCommand();
            com1.Connection = sc;
            com1.CommandText = "select Max(LOTTERY_ID) from INFO_LOTTERY";
             while (Application["sqllock"] == "lock")
                        {//检测是否已经锁住
                            System.Threading.Thread.Sleep(2000);
                        }
                        Application["sqllock"] = "lock";//上锁        
                   
                        
            string max_id = com1.ExecuteScalar().ToString();//获取数据库中最大ID
            Application["sqllock"] = "unlock";//解锁
            max_id = max_id.Remove(0, 1);
            int max_id1 = Convert.ToInt32(max_id) + 1;
            string new_id = "L" + max_id1.ToString();
            string ImagePath = "~/product_image/" + new_id + "_" + "image_tmp.jpg";
            string ImagePath2 = "~/product_image/" + new_id + "_" + "image.jpg";
            string ImagePath_tmp = Server.MapPath(ImagePath);
            string ImagePath_tmp2 = Server.MapPath(ImagePath2);
            #endregion

            File.Move(ImagePath_tmp, ImagePath_tmp2);
            File.Delete(ImagePath_tmp);
            if (File.Exists(ImagePath_tmp2) == true)
            {
            
                try
                {
                    DateTime now = DateTime.Now;
                    string start_now=now.Year+"-"+now.Month+"-"+now.Day+" "+now.Hour+":"+now.Minute+":"+now.Second;
                    string end_now = start_now;
                    SqlCommand get_count = new SqlCommand();
                    get_count.CommandText = "select count(LOTTERY_ID) from INFO_LOTTERY where LOTTERY_START<convert(smalldatetime,@start) and LOTTERY_END>convert(smalldatetime,@end) and ENTER_ID=@eid4";
                    get_count.Connection = sc;
                    get_count.Parameters.AddWithValue("@start",start_now);
                    get_count.Parameters.AddWithValue("@end",end_now);
                    get_count.Parameters.AddWithValue("@eid4", Session["ENTERID"].ToString());
                    int count_dis =Convert.ToInt32(get_count.ExecuteScalar().ToString());
                    if (count_dis == 1)
                    {
                        sc.Close();
                        Page.RegisterStartupScript("ss", "<script>alert('您的在线活动数已达限制，请等活动下架后再尝试发布新的活动！')</script>");
                        return;
                    }
                    else
                    {
                        SqlCommand insert = new SqlCommand();
                        insert.Connection = sc;
                        insert.CommandText = "insert into INFO_LOTTERY values (@id,@start,@end,@fid,@fnum,@sid,@snum,@tid,@tnum,@sume,@rules,@eid,@title,@image)";
                        insert.Parameters.AddWithValue("@id", new_id);
                        string time_start = start_year + "-" + start_month + "-" + start_day + " " + start_hour + ":" + start_minute + ":" + start_second;
                        insert.Parameters.AddWithValue("@start", time_start);
                        string time_end = end_year + "-" + end_month + "-" + end_day + " " + end_hour + ":" + end_minute + ":" + end_second;
                        insert.Parameters.AddWithValue("@end", time_end);
                        insert.Parameters.AddWithValue("@fid",fprize_id);
                        insert.Parameters.AddWithValue("@fnum",fprize_sum);
                         insert.Parameters.AddWithValue("@sid",sprize_id);
                         insert.Parameters.AddWithValue("@snum",sprize_sum);
                         insert.Parameters.AddWithValue("@tid",tprize_id);
                         insert.Parameters.AddWithValue("@tnum",tprize_sum);
                         insert.Parameters.AddWithValue("@sume",sum_expect);
                         insert.Parameters.AddWithValue("@rules",textbox9.Text);
                         insert.Parameters.AddWithValue("@eid",enterid);  
                        insert.Parameters.AddWithValue("@title", textbox1.Text);
                        insert.Parameters.AddWithValue("@image", ImagePath2);
                        while (Application["sqllock"] == "lock")
                        {//检测是否已经锁住
                            System.Threading.Thread.Sleep(2000);
                        }
                        Application["sqllock"] = "lock";//上锁
                        if (insert.ExecuteNonQuery() == 1)
                        { 
                            Application["sqllock"] = "unlock";//解锁
                            sc.Close();
                            Page.RegisterStartupScript("ss", "<script>alert('录入成功！')</script>");
                            return;
                        }
                        else
                        {
                            Application["sqllock"] = "unlock";//解锁
                            sc.Close();
                            Page.RegisterStartupScript("ss", "<script>alert('数据库异常，请重试！')</script>");
                            return;
                        }
                    }
                }
                catch (Exception c)
                {
                    sc.Close();
                    Page.RegisterStartupScript("ss", "<script>alert('" + c.Message + c.StackTrace + "Error！')</script>");
                    return;
                }
            }
            else
            {//文件重命名失败
                sc.Close();
                Page.RegisterStartupScript("ss", "<script>alert('文件重命名失败！')</script>");
                return;
            }
        }
        else
        {
            Page.RegisterStartupScript("ss", "<script>alert('需要先添加活动图片！')</script>");
            return;
        }

        
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        string FilePath = "";
        string ImagePath = "";

        SqlConnection sc = new SqlConnection(ConfigurationManager.ConnectionStrings["wbkpt"].ConnectionString.ToString());
        sc.Open();
        #region generate new id
        SqlCommand com1 = new SqlCommand();
        com1.Connection = sc;

        com1.CommandText = "select Max(LOTTERY_ID) from INFO_LOTTERY";
        while (Application["sqllock"] == "lock")
        {
            System.Threading.Thread.Sleep(2000);
        }
        Application["sqllock"] = "lock";


        string max_id = com1.ExecuteScalar().ToString();//获取数据库中最大ID
        Application["sqllock"] = "unlock";
        max_id = max_id.Remove(0, 1);
        int max_id1 = Convert.ToInt32(max_id) + 1;
        string new_id = "L" + max_id1.ToString();
        sc.Close();
        #endregion
        //上传图片文件，若不存在跳过
        if (this.FileUpload1.FileName != null && this.FileUpload1.FileName != "")
        {
            if (FileUpload1.PostedFile.ContentLength <= 0)
            {
                Page.RegisterStartupScript("ss", "<script>alert('上传图片文件为空，请重新选择文件!')</script>");
                return;
            }
            if (FileUpload1.HasFile)
            {
                if (FileUpload1.PostedFile.ContentLength > 4196304)
                {
                    Page.RegisterStartupScript("ss", "<script>alert('文件大小超过4M，请选择更小的图片上传!')</script>");
                    return;
                }
                else
                {
                    FilePath = Server.MapPath("~/product_image");
                }
                ImagePath = "~/product_image/" + new_id + "_" + "image_tmp.jpg";
                ImagePath = Server.MapPath(ImagePath);
                if (File.Exists(ImagePath))//先判断文件是否存在，若存在删除，不存在再执行操作
                    File.Delete(ImagePath);
                upload(FilePath, this.FileUpload1, new_id);
                img1.ImageUrl = "~/product_image/" + new_id + "_" + "image_tmp.jpg";

            }
            else
            {
                Page.RegisterStartupScript("ss", "<script>alert('所选路径不存在!')</script>");
                return;
            }
        }
    }
    /// <summary>
    /// 判断日期是否合法
    /// </summary>
    /// <param name="year"></param>
    /// <param name="month"></param>
    /// <param name="day"></param>
    /// <param name="hour"></param>
    /// <param name="minute"></param>
    /// <param name="second"></param>
    /// <returns></returns>
    public bool isLegal(int year, int month, int day, int hour, int minute, int second)
    {
        if (year < 0 || year > 9999)
            return false;
        if (month < 0 || month > 12)
            return false;
        if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12)
        {
            if (day < 0 || day > 31)
                return false;
        }
        else if (month == 2)
        {
            if (year % 100 == 0 && year % 400 == 0)
            {//100闰年
                if (day < 0 || day > 29)
                    return false;
            }
            else if (year % 100 != 0 && year % 4 == 0)
            {//非整百闰年
                if (day < 0 || day > 29)
                    return false;
            }
            else
            {
                if (day < 0 || day > 28)
                    return false;
            }
        }
        else
        {
            if (day < 0 || day > 31)
                return false;
        }

        return true;
    }
    public bool checkSequence(int year_start, int month_start, int day_start, int hour_start, int minute_start, int second_start, int year_end, int month_end, int day_end, int hour_end, int minute_end, int second_end)
    {
        if (year_start < year_end)
            return true;
        if (year_start > year_end)
            return false;
        if (month_start < month_end)
            return true;
        if (month_start > month_end)
            return false;
        if (day_start < day_end)
            return true;
        if (day_start > day_end)
            return false;
        if (hour_start < hour_end)
            return true;
        if (hour_start > hour_end)
            return false;
        if (minute_start < minute_end)
            return true;
        if (minute_start > minute_end)
            return false;
        if (second_start < second_end)
            return true;
        if (second_start > second_end)
            return false;
        return false;
    }
}